<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<#assign instance = "${classname?lower_case}">
<script type="text/javascript">
    require([ "dojo/_base/array", "dojo/_base/xhr", "dojo/request", "dojo/topic", "dojo/json" ],
            function(array, xhr, request, topic, JSON) {
                var deletItemsCount = 0;
                ${instance}RestForm = function(formId) {
                    dijit.byId(formId).reset();
                    if (formId.indexOf('UFD') != -1) {
                        var rowid = jQuery("#${instance}Gird").jqGrid('getGridParam', 'selrow');
                        var ${instance} = jQuery("#${instance}Gird").jqGrid('getRowData', rowid);
                        dijit.byId('${instance}UFD').setValues(${instance});
                    }
                };
                topic.subscribe("${instance}/insertOrUpdate", ${instance}RestForm);
                var syncDB = function(url, jsonData) {
                    request.post(url, {
                        data : jsonData,
                        headers : {
                            'Content-Type' : "application/json; charset=utf-8"
                        },
                        timeout : 30000
                    }).then(function(response) {
                        topic.publish("notifyMsgTopic", {
                            message : response,
                            type : "message",
                            duration : 1000
                        });
                        var currentPage = jQuery('#${instance}Gird').jqGrid('getGridParam', 'page');
                        var pageSize = jQuery('#${instance}Gird').jqGrid('getGridParam', 'rowNum');
                        var totalCount = jQuery('#${instance}Gird').jqGrid('getGridParam', 'records') - deletItemsCount;
                        var totalPages = Math.ceil(totalCount / pageSize);
                        jQuery("#${instance}Gird").jqGrid('setGridParam', {
                            page : currentPage > totalPages ? totalPages : currentPage
                        }).trigger("reloadGrid");
                    }, function(error) {
                        alert(error);
                    });
                };
                ${instance}SubmitForm = function(formId, type) {
                    var url = "${instance}/insert";
                    if (type == 'u') {
                        url = "${instance}/update";
                    }
                    var form = dijit.byId(formId);
                    if (form.isValid()) {
                        var json = JSON.stringify(form.getValues());
                        syncDB(url, json);
                        form.hide();
                        topic.publish("${instance}/insertOrUpdate", formId);
                    } else {
                        form.validate();
                    }
                };
                ${instance}Delete = function() {
                    var ids = jQuery("#${instance}Gird").jqGrid('getGridParam', 'selarrrow') || [];
                    deletItemsCount = ids.length;
                    if (ids.length > 0) {
                        if (confirm('确认删除所选定的项？')) {
                            var ${instance} = {};
                            ${instance}.id = '';
                            array.forEach(ids, function(entry, i) {
                                ${instance}.id += entry + ",";
                            });
                            syncDB("${instance}/delete", JSON.stringify(${instance}));
                        }
                    } else {
                        alert('请选择至少一条数据!');
                    }
                };
                ${instance}Query = function(formId) {
                    var ${instance} = dijit.byId(formId).getValues();
                    jQuery("#${instance}Gird").jqGrid('setGridParam', {
                        postData : ${instance},
                        mtype : "post"
                    }).trigger('reloadGrid');
                };
            });
</script>
<div data-dojo-type="dijit/Dialog" id="${instance}IFD" title="新增">
  <div class="dijitDialogPaneContentArea">
    <table>
    <#list tableMetaData.columns as columnMetaData>
    <#if tableMetaData.primaryKeys?seq_contains(columnMetaData.columnName)>
    <#else>
      <tr>
        <td><label for="${columnMetaData.columnName}">${columnMetaData.columnRemark!columnMetaData.columnName}: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, trim:true" type="text"
          name="${columnMetaData.columnName}"></td>
      </tr>
    </#if>
    </#list>
    </table>
  </div>
  <div class="dijitDialogPaneActionBar">
    <button data-dojo-type="dijit/form/Button" type="button" onclick="${instance}SubmitForm('${instance}IFD','i')">保存</button>
    <button data-dojo-type="dijit/form/Button" type="button" onclick="${instance}RestForm('${instance}IFD');">重置</button>
  </div>
</div>
<div data-dojo-type="dijit/Dialog" id="${instance}UFD" title="更新">
  <div class="dijitDialogPaneContentArea">
    <#list tableMetaData.primaryKeys as pk>
    <input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true, readOnly: true" type="text"
      name="${pk}" style="display: none;">
    </#list>
    <table>
    <#list tableMetaData.columns as columnMetaData>
    <#if tableMetaData.primaryKeys?seq_contains(columnMetaData.columnName)>
    <#else>
      <tr>
        <td><label for="${columnMetaData.columnName}">${columnMetaData.columnRemark!columnMetaData.columnName}: </label></td>
        <td><input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required: true" type="text"
          name="${columnMetaData.columnName}"></td>
      </tr>
    </#if>
    </#list>
    </table>
  </div>
  <div class="dijitDialogPaneActionBar">
    <button data-dojo-type="dijit/form/Button" type="button" onclick="${instance}SubmitForm('${instance}UFD','u')">保存</button>
    <button data-dojo-type="dijit/form/Button" type="button" onclick="${instance}RestForm('${instance}UFD');">重置</button>
  </div>
</div>
<fieldset>
  <legend>&nbsp;&nbsp;信息选项&nbsp;&nbsp;</legend>
  <form id="query${classname}Form" data-dojo-type="dijit/form/Form" method="post">
    <div style="margin-left: 5px;">
      <table>
      <#list tableMetaData.columns as columnMetaData>
      <#if tableMetaData.primaryKeys?seq_contains(columnMetaData.columnName)>
      <#else>
        <tr>
          <td><label for="${columnMetaData.columnName}">${columnMetaData.columnRemark!columnMetaData.columnName}: </label></td>
          <td><input data-dojo-type="dijit/form/TextBox" data-dojo-props="trim: true" type="text" name="${columnMetaData.columnName}"></td>
        </tr>
      </#if>
      </#list>
      </table>
    </div>
  </form>
  <div style="padding: 5px;">
    <button id="${instance}InsertBtn" data-dojo-type="dijit/form/Button" type="submit" label="新增">
      <script type="dojo/method" event="onClick" args="evt">
        dijit.byId('${instance}IFD').show();
      </script>
    </button>
    <button id="${instance}DeleteBtn" data-dojo-type="dijit/form/Button" type="button" label="删除" onclick="${instance}Delete();"></button>
    <button id="${instance}UpdateBtn" data-dojo-type="dijit/form/Button" type="button" label="更新">
      <script type="dojo/method" event="onClick" args="evt">
        var ids = jQuery("#${instance}Gird").jqGrid('getGridParam', 'selarrrow') || [];
        if (ids.length != 1) {
          alert('每次只能修改一条数据!');
        }else{
          var ${instance} = jQuery("#${instance}Gird").jqGrid('getRowData', ids[0]);
          dijit.byId('${instance}UFD').setValues(${instance});
          dijit.byId('${instance}UFD').show();
        }
      </script>
    </button>
    <button id="${instance}QueryBtn" data-dojo-type="dijit/form/Button" type="button" label="查询"
      onclick="${instance}Query('query${classname}Form');"></button>
  </div>
</fieldset>
<div id="gird">
  <table id="${instance}Gird"></table>
  <div id="${instance}Toolbar"></div>
</div>
<script type="text/javascript">
    jQuery("#${instance}Gird").jqGrid({
        url : '${instance}/queryAsList',
        datatype : "json",
        autowidth : true,
        rownumbers : true,
        height : 'auto',
        colNames : [
        <#list tableMetaData.columns as columnMetaData>
          '${columnMetaData.columnRemark!columnMetaData.columnName}'<#if columnMetaData_has_next>,</#if>
        </#list>
        ],
        colModel : [ 
        <#list tableMetaData.primaryKeys as pk>
        {
          name : '${pk}',
          index : '${pk}',
          width : 60,
          key : true,
          hidden : true,
          align : 'center'
        },
        </#list>
        <#list tableMetaData.columns as columnMetaData>
        <#if tableMetaData.primaryKeys?seq_contains(columnMetaData.columnName)>
        <#else>
        {
          name : '${columnMetaData.columnName}',
          index : '${columnMetaData.columnName}',
          align : 'center'
        }<#if columnMetaData_has_next>,</#if>
        </#if>
        </#list>
        ],
        rowNum : 15,
        rowList : [ 15, 20, 25, 30 ],
        pager : '#${instance}Toolbar',
        // sortname : 'username',
        recordpos : 'right',
        viewrecords : true,
        sortorder : "desc",
        jsonReader : {
            repeatitems : false
        },
        multiselect : true,
        shrinkToFit : false,
        caption : "${tableMetaData.tableRemark!tableMetaData.tableName}列表"
    });
    jQuery("#${instance}Gird").jqGrid('navGrid', '#${instance}Toolbar', {
        edit : false,
        add : false,
        del : false,
        search : false,
        refresh : true
    });
</script>
